﻿namespace Digitalmes.Application.Sys.Users.Commands;

/// <summary>
/// 给用户分配角色命令
/// </summary>
/// <param name="UserId"></param>
/// <param name="RoleIds"></param>
public record DistributeRolesToUserCommand(long UserId, long[] RoleIds) : IRequest<IResult<bool>>;

internal sealed class DistributeMenusToRoleCommandHandler(IRepository<SysUserRole> repo) : IRequestHandler<DistributeRolesToUserCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(DistributeRolesToUserCommand request, CancellationToken cancellationToken)
    {
        List<SysUserRole> userRoles = request.RoleIds
            .Distinct()
            .Select(roleId => new SysUserRole
            {
                UserId = request.UserId,
                RoleId = roleId,
            }).ToList();

        // 删除原有的映射关系
        await repo.DeleteAsync(m => m.RoleId == request.UserId, cancellationToken);

        // 添加新的映射关系
        var result = await repo.InsertRangeAsync(userRoles, cancellationToken);
        return Result.From(result);
    }
}
